<?php

/** Zend_Controller_Action */
require_once ROOT_PATH . '/library/Soooner/Controller/Action.php';

class IndexController extends Soooner_Controller_Action
{
	private $_roleid;
    private $_modelMenu;
    private $_modelAdmin;

    public function init()
    {
        /* Initialize action controller here */
    	$this->initDzTemplate();
    }

    public function indexAction()
    {
        // action body
        $id=2;
        if($this->_configs["state"]=="slave")$id=35;
        include $this->_dzTemplate->getFile( 'index.html' );
    }

    public function topAction()
    {
    	$filter = "3,2,6,7";//主3,2,6,7从1,3,5,7代理4,5,6,7
    	if($this->_configs["state"]=="slave")$filter = "1,3，5,7";
    	if($this->_configs["state"]=="master"){
    		if($this->_configs["isproxy"]){//代理
    			$filter = "4,5,6,7";
    		}else{
    			$filter = "3,2,6,7";
    		}
    	}
    	$this->_modelMenu = new Model_Tables_Menu();
    	$infos = $this->_modelMenu->getChild(1,$filter);
    	$session = $this->_userinfo;//用户信息
    	$_modelRole = new Model_Tables_Role();
    	$roleInfo = $_modelRole->getInfos($session["roles"]);    	
    	//print_r($this->_configs);exit;
        include $this->_dzTemplate->getFile( 'top.html' );
    }

    public function menuAction()
    {
        $menuid = intval($this->_getParam('menuid'));
        if (!$menuid) $menuid = 2;  //2：常用菜单
        $this->_modelMenu = new Model_Tables_Menu();
        $result = $this->_modelMenu->get($menuid);
        $timestamp = time();
        include $this->_dzTemplate->getFile( 'menu.html' );
    }

    public function dragAction()
    {
        include $this->_dzTemplate->getFile( 'drag.html' );
    }

    public function mainAction()
    {
        //echo '<pre>userinfo:';print_r($this->_userinfo);
        //echo '<br>spinfo:';print_r($this->_spinfo);
        //echo '<br>processlistbyuser';print_r($this->_processlistbyuser );          
    	include $this->_dzTemplate->getFile( 'main.html' );
    	//$this->_redirect("/content/index0/catid/78/contenttype/0/");
    }

    public function loginAction()
    {
        $request = $this->getRequest();
        if ($request->isPost())
        {
            $f = new Zend_Filter_StripTags();
            $params = $request->getPost();
            $username = $f->filter($params['username']);
            $password = $f->filter($params['password']);

            $forward = $params['forward'];
            $validatecode = $params['validatecode'];

            if (empty($this->_session->checkcode))
            {
				exit('<script type="text/javascript" charset="utf-8">alert("验证码已过期");history.back();</script>');
                //throw new Exception('验证码已过期');
            }
            else if (empty($validatecode)||$validatecode!=$this->_session->checkcode)
            {
				exit('<script type="text/javascript" charset="utf-8">alert("验证码错误");history.back();</script>');
                //throw new Exception('验证码错误');
            }
            else if (!empty($username) && !empty($password))
            {
	            $dbAdapter = Zend_Db_Table::getDefaultAdapter();
	            $authAdapter = new Zend_Auth_Adapter_DbTable(
	                $dbAdapter,
	                'admin',
	                'username',
	                'password',
	                'MD5(?) AND disabled = 0'
	            );
	            $authAdapter->setIdentity($username)
	                        ->setCredential($password);
	            $result = $authAdapter->authenticate();

	            //建立持久连接
	            if ($result && $result->isValid())
	            {
	                if ($request->getPost('rememberMe'))
	                { //记住密码
	                    Zend_Session::rememberMe('315360000');
	                }
	                else
	                {
	                    Zend_Session::forgetMe();
	                }
//                    $this->_modelAdmin = new Model_Tables_Admin();
                    $userinfo = $authAdapter->getResultRowObject(array('userid', 'username', 'roles', 'issp', 'spid'));
//                    $admininfo = $this->_modelAdmin->getInfo($userinfo->userid);
                    $roles = empty($userinfo->roles) ? '' : substr($userinfo->roles, 1, -1);
//                    $userinfo->roles = $roles;
					$dbAdapter->query("UPDATE `admin` SET `lastloginip`='{$_SERVER["REMOTE_ADDR"]}',`lastlogintime`=NOW(),`logintimes`=`logintimes`+1 WHERE `username`='{$username}' ");
	                $this->_auth->getStorage()->write($userinfo);
                    exit('<script>window.location.href=\'/index\'</script>');
//	                $this->_forward('/index/');
	            }
	            else
	            {
					exit('<script type="text/javascript" charset="utf-8">alert("用户名或密码错误");history.back();</script>');
	                //throw new Exception('用户名或密码错误');
	            }
            }
//            $this->_redirect('/index/');
        }
    	$time = explode(' ', microtime());
    	$time = (float)($time[1]+(float)$time[0]);
        include $this->_dzTemplate->getFile( 'login.html' );
    }

    public function logoutAction()
    {
        $this->_auth->clearIdentity();
        exit('<script>window.location.href=\'/\'</script>');
//        $this->_redirect( $url );
    }

    public function ajaxAction()
    {
    	$type = $this->_getParam('type');
    	if (empty($type))
    	{
    		throw new Exception('未知操作');
    	}
    	if ('validate' == $type)
    	{
            $validatecode = $this->_getParam('validatecode');
            if (empty($this->_session->checkcode))
            {
            	echo 'reload';
            }
    		else if (empty($validatecode)||$validatecode!=$this->_session->checkcode)
    		{
    			echo 'fail';
    		}
    		else
    		{
    			echo 'succ';
    		}
    		exit;
    	}
    }

    public function capAction()
    {
        $enablegd = 1;
		$funcs = array('imagecreatetruecolor','imagecolorallocate','imagefill','imageline','imagedestroy','imagecolorallocatealpha','imageellipse','imagepng');
		foreach($funcs as $func)
        {
            if(!function_exists($func))
            {
                $enablegd = 0;
                break;
            }
        }
        if(!function_exists('ob_gzhandler')) ob_clean();

        if($enablegd)
        {
		    //create captcha
		    $consts = '23456789';
		    $vowels = '23456789';
		    //$consts = 'cdfgkmnpqrstwxyz23456';
		    //$vowels = 'aek23456789';
		    for ($x = 0; $x < 6; $x++)
		    {
		        $const[$x] = substr($consts, mt_rand(0,strlen($consts)-1),1);
		        $vow[$x] = substr($vowels, mt_rand(0,strlen($vowels)-1),1);
		    }
		    $radomstring = $const[0] . $vow[0] .$const[2] . $const[1] . $vow[1] . $const[3] . $vow[3] . $const[4];
		    $this->_session->checkcode = $string = substr($radomstring,0,4); //only display 4 str
		    //set up image, the first number is the width and the second is the height
		    $imageX = strlen($radomstring)*8;   //the image width
		    $imageY = 20;                       //the image height
		    $im = imagecreatetruecolor($imageX,$imageY);

		    //creates two variables to store color
		    $background = imagecolorallocate($im, rand(180, 250), rand(180, 250), rand(180, 250));
		    $foregroundArr = array(imagecolorallocate($im, rand(0, 20), rand(0, 20), rand(0, 20)),
		                           imagecolorallocate($im, rand(0, 20), rand(0, 10), rand(245, 255)),
		                           imagecolorallocate($im, rand(245, 255), rand(0, 20), rand(0, 10)),
		                           imagecolorallocate($im, rand(245, 255), rand(0, 20), rand(245, 255)));
		    $foreground2 = imagecolorallocatealpha($im, rand(20, 100), rand(20, 100), rand(20, 100),80);
		    $middleground = imagecolorallocate($im, rand(200, 160), rand(200, 160), rand(200, 160));
		    $middleground2 = imagecolorallocatealpha($im, rand(180, 140), rand(180, 140), rand(180, 140),80);

		    //fill image with bgcolor
		    imagefill($im, 0, 0, imagecolorallocate($im, 250, 253, 254));
		    //writes string
		    imagettftext($im, 12, rand(30, -30), 5, rand(14, 16), $foregroundArr[rand(0,3)], ROOT_PATH.'/public/images/ALGER.TTF', $string[0]);
		    imagettftext($im, 12, rand(50, -50), 20, rand(14, 16), $foregroundArr[rand(0,3)], ROOT_PATH.'/public/images/ARIALNI.TTF', $string[1]);
		    imagettftext($im, 12, rand(50, -50), 35, rand(14, 16), $foregroundArr[rand(0,3)], ROOT_PATH.'/public/images/ALGER.TTF', $string[2]);
		    imagettftext($im, 12, rand(30, -30), 50, rand(14, 16), $foregroundArr[rand(0,3)], ROOT_PATH.'/public/images/arial.ttf', $string[3]);

		    //strikethrough

		    $border = imagecolorallocate($im, 133, 153, 193);
		    //imagefilledrectangle($aimg, 0, 0, $x_size - 1, $y_size - 1, $back);
		    imagerectangle($im, 0, 0, $imageX - 1, $imageY - 1, $border);

		    $pointcol = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
		    for ($i=0;$i<80;$i++)
		    {
		        imagesetpixel($im,rand(2,$imageX-2),rand(2,$imageX-2),$pointcol);
		    }
		    //random shapes
		    for ($x=0; $x<9;$x++)
		    {
		        if(mt_rand(0,$x)%2==0)
		        {
		            imageline($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 999999));
		            imageellipse($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), $middleground2);
		        }
		        else
		        {
		            imageline($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 999999));
		            imageellipse($im, rand(0, 120), rand(0, 120), rand(0, 120), rand(0, 120), $middleground);
		        }
		    }
		    //output to browser
		    header("content-type:image/png\r\n");
		    imagepng($im);
		    imagedestroy($im);
        }
		else
		{
		    $files = glob(ROOT_PATH.'/public/images/captcha/*.jpg');
		    if(!is_array($files)) exit('请检查验证码图片目录');

		    $checkcodefile = $files[rand(0, count($files)-1)];
		    $this->_session->checkcode = substr(basename($checkcodefile), 0, 4);

		    header("content-type:image/jpeg\r\n");
		    include $checkcodefile;
		}
    }

    public function listmenuAction()
    {
        $menuid = intval($this->_getParam('menuid'));
        if ($_REQUEST['root'] != "source") $menuid = intval($_REQUEST['root']);
        $menuid = empty($menuid) ? 2 : $menuid;
        $this->_modelMenu = new Model_Tables_Menu();
        $result = $this->_getChild($menuid);
        $OResult = array();
        foreach ($result as $i)
        {
        	if ($i['target']=="right")
        	{
				//$i['url'] = $i['isfolder'] ? 'javascript:void(0);' : $i['url'];
        		$i['name'] = '<a href=\''.$i['url'].'\' target=\''.$i['target'].'\'>'.$i['name'].'</a>';
        	}
        	$OResult[] = array('text'=>$i['name'],'id'=>$i['menuid'],'hasChildren'=>( $i['isfolder']? true:false )) ;
        }
        echo json_encode($OResult);
        exit;
    }

    private function _getChild($menuid = 0)
    {
    	$filter = "3,2,6,7";//主3,2,6,7从1,3,5,7代理4,5,6,7
    	if($this->_configs["state"]=="slave")$filter = "1,3，5,7";
    	if($this->_configs["state"]=="master"){
    		if($this->_configs["isproxy"]){//代理
    			$filter = "4,5,6,7";
    		}else{
    			$filter = "3,2,6,7";
    		}
    	}
    	//$filter = "3,2";
    	//if($this->_configs["state"]=="slave")$filter = "1,3";
        $menuid = intval($menuid);
        $result = $this->_modelMenu->getMenuList($menuid,$filter);
        
        $rolesarr = explode(',', $this->_userinfo['roles']);
        /*if (!is_array($rolesarr)||empty($rolesarr))
        {
        	return array();
        }*/
        if (in_array(1,$rolesarr))
        {
        	return $result;
        }
        foreach($result as $k=>$r)
        {
         	$args = explode("/",$r['url']);
            $resource=$args[1];
            $action=$args[2];
            if($action=="")$action="index";
            if($r['isfolder']==1)
            {
               $sub=$this->_getChild($r["menuid"]);
               if(count($sub)==0)
                        unset($result[$k]);
                continue;
            }
            try{
                $allow=$this->checkAllow($resource,$action,true);
                if(!$allow)unset($result[$k]);
            }
            catch(Exception $e)
            {
                unset($result[$k]);
            }
        }
        return $result;
    }

    public static function check_in($id, $ids = '', $s = ',')
    {
        if(!$ids) return false;
        $ids = explode($s, $ids);
        return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
    }

}
